package bean;

import java.util.ArrayList;
import java.util.Collections;

public class Hand {
	private ArrayList<Card> cards = new ArrayList<Card>(13);

	public Hand() {

	}

	public Hand(String s) {
		String[] cardStrings = s.split(",");
		for (String cardString : cardStrings) {
			Card c = new Card(cardString);
			cards.add(c);
		}
	}

	public ArrayList<Card> getCards() {
		return cards;
	}

	public void setCards(ArrayList<Card> cards) {
		this.cards = cards;
	}

	public int getSize() {
		return cards.size();
	}

	public ArrayList<Card> getAvailableCards(int suit) {
		this.sortHand();
		ArrayList<Card> result = new ArrayList<Card>(13);
		int lastCardId = -3;
		// pick all card with the same suit
		if (suit != Card.NOTRUMP) {
			for (Card c : cards) {
				int thisCardId = (4 - c.getSuit()) * 60 + c.getRank();
				if (c.getSuit() == suit && thisCardId > lastCardId + 1) {
					result.add(c);
				}
				lastCardId = thisCardId;
			}
		}

		// pick any card
		if (result.size() == 0) {
			lastCardId = -3;
			for (Card c : cards) {
				int thisCardId = (4 - c.getSuit()) * 60 + c.getRank();
				if (thisCardId > lastCardId + 1) {
					result.add(c);
				}
				lastCardId = thisCardId;
			}
		}
		return result;
	}

	public void sortHand() {
		Collections.sort(cards);
	}

	public String toString() {
		if (this.getCards() == null)
			return "";
		StringBuffer result = new StringBuffer();
		for (Card c : cards) {
			result.append(c.toString());
			if (!cards.get(cards.size() - 1).equals(c))
				result.append(",");
		}
		return result.toString();
	}

	public String toEncode() {
		if (this.getCards() == null)
			return "";
		StringBuffer result = new StringBuffer();
		for (Card c : cards) {
			result.append(c.getCardEncode());
		}
		return result.toString();
	}

	public void addCard(Card c) {
		if (!cards.contains(c))
			cards.add(c);
	}

	public boolean playCard(Card c) {
		return cards.remove(c);
	}

	@SuppressWarnings("unchecked")
	public Hand clone() {
		Hand clonedHand = new Hand();
		clonedHand.setCards((ArrayList<Card>) cards.clone());
		return clonedHand;
	}
}
